package com.bjsxt.service.impl;

import com.bjsxt.mapper.MenuMapper;
import com.bjsxt.pojo.Menu;
import com.bjsxt.pojo.PageA;
import com.bjsxt.pojo.TreeA;
import com.bjsxt.service.MenuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<TreeA> findMenus(Integer aid, Integer pid) {
        List<Menu> menus = menuMapper.selectMenus(aid, pid);
        List<TreeA> list= new ArrayList<>();
        for (Menu menu:menus){
            TreeA treeA = new TreeA(menu.getMid(),menu.getMname(),menu.getStatus()==0?"closed":"open",menu.getUrl());
            list.add(treeA);
        }
        return list;
    }

    @Override
    public PageA<Menu> findAllMenu(Integer page, Integer rows) {
        Page pg = PageHelper.startPage(page, rows);
        List<Menu> menus = menuMapper.selectAllMenu();
        PageA<Menu> pga=new PageA<>(menus,pg.getTotal());
        return pga;
    }

    @Override
    public List<TreeA> findAllMenu2(Integer pid) {
        List<Menu> menus = menuMapper.selectAllMenu2(pid);
        List<TreeA> list= new ArrayList<>();
        for (Menu menu:menus){
            TreeA treeA = new TreeA(menu.getMid(),menu.getMname(),menu.getStatus()==0?"closed":"open",menu.getUrl());
            list.add(treeA);
        }
        return list;
    }

    @Override
    public Integer addMenu(Menu menu) {
        return menuMapper.insertMenu(menu);
    }

    @Override
    public Integer changeMenu(Menu menu) {
        return menuMapper.updateMenu(menu);
    }

    @Override
    public Integer removeMenu(Integer mid) {
        List<Menu> menus = menuMapper.selectAllMenu2(mid);
        if (menus.size()>0){
            return -1;
        }else {
            return menuMapper.deleteMenu(mid);
        }
    }

    @Override
    public List<TreeA> findAllMenu3() {
        //一级菜单
        List<TreeA> list = menuMapper.selectAllMenu3(0);
        for (TreeA t:list){
            Integer mid = t.getId();
            List<TreeA> list1 = menuMapper.selectAllMenu3(mid);
            t.setChildren(list1);
        }
        return list;
    }
}
